﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;

namespace Site.Secure
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            SqlDataSource1.SelectCommand = "SELECT * FROM Users WHERE userID='" + edtUser.Text + "' AND userPass='" + edtPass.Text + "'";
            DataSourceSelectArguments Select = new DataSourceSelectArguments();
            DataView View = (DataView)SqlDataSource1.Select(Select);

            if (View.Count == 1) //The User was found and Password is Correct
            {
                try
                {
                    System.Web.Security.FormsAuthentication.SetAuthCookie(View.Table.Rows[0]["userID"].ToString(), false);
                    Session["userID"] = edtUser.Text;
                    Session["userType"] = View.Table.Rows[0]["userType"].ToString();
                    string Return = Request.QueryString["ReturnUrl"];
                    Logger.Log("User '" + edtUser.Text + "' Logged On", "LOG ON", Server);
                    if(Return == null)
                    {
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        if(Request.QueryString["ReturnUrl"] == "%2fSecure")
                            Response.Redirect("Default.aspx");
                        else
                        Response.Redirect(Request.QueryString["ReturnUrl"]);
                    }
                }
                catch (HttpException ex)
                {
                    if (ex.ErrorCode == -2147467259) //SSL Error Here
                    {
                        lblStatus.Text = "SSL Error, Can't Login!";
                    }
                }
            }
            else
            {
                lblStatus.Text = "Bad Credentials, Can't Login!";
            }
        }
    }
}